package gui;

import database.worker.DBTrackWorker;
import database.worker.IDoneListener;
import dto.Event;
import dto.Track;
import gui.cell.TrackCellRenderer;
import gui.cell.TrackEventCellRenderer;
import gui.model.TrackFilterableListDataModel;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.List;
import java.util.ResourceBundle;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import map.MapManager;
import org.jdesktop.swingx.mapviewer.GeoPosition;

/**
 * The start Panel to get an overview over all tracks and to select one
 * 
 * @author Pascal
 */
public class StartPanel extends javax.swing.JPanel {
    
    private MainWindow mainWindow; //to navigate to the trackPanel
    
    /**
     * Creates new form StartWindow
     */
    public StartPanel(MainWindow mainWindow) {
        if (mainWindow == null) {
            throw new NullPointerException();
        }
        
        
        
        this.mainWindow = mainWindow;
        
        tracksListModel = new TrackFilterableListDataModel();
        //timelineListModel = new DefaultListModel<>();
        
        initComponents();
        mapView.setAddressLocation(new GeoPosition(49.23553769843449, 6.974054574966431));
        mapView.setZoom(3);
        textSearch.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                textSearchTextChanged();
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                textSearchTextChanged();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                textSearchTextChanged();
            }
        });
        
        DBTrackWorker worker = new DBTrackWorker();
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        worker.setDoneListener(new IDoneListener() {

            @Override
            public void done(Object arg) {
                List<Track> tracks = (List<Track>)arg;
                
                for (Track t: tracks) {
                    addTrack(t);
                }
                
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            }
        });
        worker.execute();
        
        listviewTracks.addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e) {
                listSelectionActionPerformed(e);
            }
        });
    }
    
    /**
     * returns selected track of listviewTracks
     * @return selected track
     */
    public Track getListviewTrackselected(){
        return (Track)listviewTracks.getSelectedValue();   
        
    }
    
    /**
     * deletes the selected track
     */
    public void removeSelectedTrack(){
        if (getListviewTrackselected() != null){
            int result = javax.swing.JOptionPane.showConfirmDialog(null, ResourceBundle.getBundle("gui/guilabels").getString("deleteTrack"), ResourceBundle.getBundle("gui/guilabels").getString("deleteTrackTitel"), javax.swing.JOptionPane.YES_NO_OPTION);
            if (result == javax.swing.JOptionPane.YES_OPTION) {
                DBTrackWorker worker = new DBTrackWorker(DBTrackWorker.Type.DeleteTrack, getListviewTrackselected());
                worker.execute();
                
                tracksListModel.remove(listviewTracks.getSelectedIndex());
            }
        }
    }
    
    /**
     * opens create track window
     * 
     */
    public void createNewTrack(){
        AddEditTrack newTrackDialog = new AddEditTrack();
        newTrackDialog.setVisible(true);        
        if (newTrackDialog.getTrack() != null && newTrackDialog.getTrack().getName() != null){
            addTrack(newTrackDialog.getTrack());            
        }
        newTrackDialog.dispose();
    }
    
    public void listSelectionActionPerformed(ListSelectionEvent e){
         if (e.getValueIsAdjusting() == false) {
            if (listviewTracks.getSelectedIndex() != -1){
                
                final Track track = getListviewTrackselected();
                
                DBTrackWorker worker = new DBTrackWorker(DBTrackWorker.Type.GetEventsByTrack, track);
                worker.setDoneListener(new IDoneListener() {

                    @Override
                    public void done(Object arg) {
                        List<Event> events = (List<Event>)arg;
                        Collections.sort(events);
                        track.setEvents(events);
                        listviewTimeline.setModel(track.getEvents());
                    }
                });
                worker.execute();
                
//                for (Event evt : track.getEvents()) {
//                    timelineListModel.addElement(evt);
//                }
                map.MapManager mManager = new MapManager(mapView);                
                track.setTrackList(mManager.importGPX(track.getGpxFilePath()));
            }             
         }
    }
    
    /**
     * add track on tracksListModel
     * @param track 
     */
    public void addTrack(Track track) {
        if (track == null) {
            throw new NullPointerException();
        }
        
        tracksListModel.add(track);
    }
    
    private void textSearchTextChanged() {
        tracksListModel.setFilter(textSearch.getText());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        jSplitPane2 = new javax.swing.JSplitPane();
        jScrollPane2 = new javax.swing.JScrollPane();
        listviewTimeline = new javax.swing.JList();
        mapView = new org.jdesktop.swingx.JXMapKit();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listviewTracks = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textSearch = new javax.swing.JTextField();

        setLayout(new java.awt.BorderLayout());

        jSplitPane1.setDividerLocation(240);

        jSplitPane2.setDividerLocation(550);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        listviewTimeline.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listviewTimeline.setCellRenderer(new TrackEventCellRenderer());
        jScrollPane2.setViewportView(listviewTimeline);

        jSplitPane2.setBottomComponent(jScrollPane2);

        mapView.setDefaultProvider(org.jdesktop.swingx.JXMapKit.DefaultProviders.OpenStreetMaps);
        mapView.setMiniMapVisible(false);
        jSplitPane2.setLeftComponent(mapView);

        jSplitPane1.setRightComponent(jSplitPane2);

        jPanel1.setLayout(new java.awt.BorderLayout());

        listviewTracks.setModel(tracksListModel);
        listviewTracks.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        listviewTracks.setCellRenderer(new TrackCellRenderer());
        listviewTracks.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                listviewTracksMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(listviewTracks);

        jPanel1.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel2.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 0));
        jPanel2.setLayout(new java.awt.BorderLayout(5, 5));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/resources/magnifier.png"))); // NOI18N
        jPanel2.add(jLabel1, java.awt.BorderLayout.WEST);

        textSearch.setColumns(20);
        jPanel2.add(textSearch, java.awt.BorderLayout.CENTER);

        jPanel1.add(jPanel2, java.awt.BorderLayout.PAGE_END);

        jSplitPane1.setLeftComponent(jPanel1);

        add(jSplitPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void listviewTracksMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_listviewTracksMouseClicked
        if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
            //left mouse double click
            mainWindow.setTrackPanel(this.getListviewTrackselected());
        }
    }//GEN-LAST:event_listviewTracksMouseClicked
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JList listviewTimeline;
    private javax.swing.JList listviewTracks;
    private org.jdesktop.swingx.JXMapKit mapView;
    private javax.swing.JTextField textSearch;
    // End of variables declaration//GEN-END:variables
    private TrackFilterableListDataModel tracksListModel;
    //private DefaultListModel<ITrackEventData> timelineListModel;
}
